//CountReducer.dart
import 'package:flutter_demo/ui/redux/actions/CountAction.dart';
import 'package:flutter_demo/ui/redux/states/CountState.dart';
import 'package:redux/redux.dart';

// 以下用两种方式创建 reducer
// 1. 基本的 switch-case
// 2. 使用 combineReducers + TypedReducer

//CountState countReducer(state, action) {
//  switch (action.runtimeType) {
//    case IncrementCountAction:
//      return CountState(state.count + 1);
//
//    case DecrementCountAction:
//      return CountState(state.count - 1);
//
//    case SetCountAction:
//      return CountState((action as SetCountAction).value);
//
//    default:
//      return state;
//  }
//}

// 使用 combineReducers 避免写 switch-case
// TypedReducer 的作用就是将 Function 与 Action 关联
final countReducer = combineReducers<CountState>([
  TypedReducer<CountState, IncrementCountAction>(_increment),
  TypedReducer<CountState, DecrementCountAction>(_decrement),
  TypedReducer<CountState, SetCountAction>(_set),
]);

CountState _increment(state, action) => CountState(state.count + 1);
CountState _decrement(state, action) => CountState(state.count - 1);
CountState _set(state, SetCountAction action) => CountState(action.value);